package twopointer;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class Solution_15 {

    /**
     * 这种是基于两数之和的思路，但是会有重复
     */
 /*   public List<List<Integer>> threeSum(int[] nums) {
        Arrays.sort(nums);
        List<List<Integer>> res = new ArrayList<>();
        Map<Integer, Integer> map = new HashMap<>();
        for (int i = 0; i < nums.length; i++) {
            int target = -nums[i];
            for (int j = i; j < nums.length; j++) {
                if (map.containsKey(target - nums[j])) {
                    List<Integer> list = new ArrayList<>();
                    list.add(nums[i]);
                    list.add(target - nums[j]);
                    list.add(nums[j]);
                    res.add(list);
                }
                map.put(nums[j], j);
            }
        }
        return res;
    }*/
    public List<List<Integer>> threeSum(int[] nums) {
        List<List<Integer>>res=new ArrayList<>();
        Arrays.sort(nums);
        for (int i = 0; i < nums.length-2; i++) {
            int target=-nums[i];
            if(i>0&&nums[i]==nums[i-1])
                continue;
            int left=i+1,right=nums.length-1;
            while (left<right){
                int sum=nums[left]+nums[right];
                if(sum<target)
                    left++;
                else if(sum>target)
                    right--;
                else {
                    res.add(Arrays.asList(nums[i], nums[left], nums[right]));
                    while (left<right&&nums[left]==nums[left+1])
                        left++;
                    while (left<right&&nums[right]==nums[right-1])
                        right--;
                    left++;
                    right--;
                }
            }
        }
        return res;
    }

    public static void main(String[] args) {
        Solution_15 solution15 = new Solution_15();
        System.out.println(solution15.threeSum(new int[]{-1, 0, 1, 2, -1, -4}));
    }
}
